package model

import (
	"fmt"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type (
	BrandModel struct {
		db *gorm.DB
	}
	BrandConf struct {
		ID            int64          `gorm:"primary key" json:"id"`
		Brand         string         `gorm:"type:varchar(40)" json:"brand"`         //品牌
		Specification string         `gorm:"type:varchar(40)" json:"specification"` //型号
		ModelId       string         `gorm:"type:varchar(20)"  json:"model_id"`     //所属物模型
		Protocol      string         `gorm:"type:varchar(20)" json:"protocol"`      //所用协议
		Monitor       string         `gorm:"monitor"  json:"monitor"`               //监测项目
		Param         datatypes.JSON `gorm:"param"  json:"param"`
	}
	BrandParam struct {
		IP       string
		Port     string
		Name     string
		Baud     string
		Parity   string
		StopBits string
		DataBit  string
		IsModbus bool
		SlaveID  int
	}
)

func NewBrandModel(db *gorm.DB) *BrandModel {
	return &BrandModel{
		db: db,
	}
}

func (m *BrandModel) Add(brand BrandConf) error {
	return m.db.Model(&BrandConf{}).Create(brand).Error
}

func (m *BrandModel) Del(id int64) error {
	return m.db.Model(&BrandConf{}).Delete("id = ?", id).Error
}

func (m *BrandModel) GetBrandList() ([]string, error) {
	var data []string
	err := m.db.Model(&BrandConf{}).Distinct("brand").Scan(&data).Error
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (m *BrandModel) GetBrandSpec(Brand string) ([]string, error) {
	var specification []string
	err := m.db.Model(&BrandConf{}).Select("specification").Where("brand = ?", Brand).Scan(&specification).Error
	if err != nil {
		return nil, err
	}
	return specification, nil
}

func (m *BrandModel) GetBrandParam(brand, specification string) (interface{}, error) {
	var data BrandConf
	err := m.db.Model(&BrandConf{}).Where("brand = ? and specification = ?", brand, specification).Find(&data).Error
	if err != nil {
		return nil, err
	}
	var params BrandParam
	err = data.Param.Scan(&params)
	if err != nil {
		fmt.Println("jsonp unMarshal err:", err)
	}
	return params, err
}

func (m *BrandModel) Get() {

}
